package com.harmontronics.hanma.paas.paas.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
public final class FileUtil {

    private FileUtil() {}

    public static boolean checkFileSize(Long len,int size,String unit){
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }



    public static File getResourceFile(String resourceFileName) {
        return new File(FileUtil.class.getClassLoader().getResource(resourceFileName).getPath());
    }

    public static String getResourceFileContent(String resourceFileName) throws IOException {
        return IOUtils.toString(
                FileUtil.class.getClassLoader().getResourceAsStream(resourceFileName), "UTF-8");
    }

    public static String getFileContent(File file) throws IOException {
        return FileUtils.readFileToString(file, "UTF-8");
    }

    public static boolean isFilenameValid(String file) {
        File f = new File(file);
        try {
            f.getCanonicalPath();
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    public static boolean createFloderIfNotExist(String floderPath) {
        File file = new File(floderPath);
        if (!file.exists()) {
            try {
                Files.createDirectories(Paths.get(floderPath));
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }

        if (!file.isDirectory()) {
            return false;
        }

        return true;
    }

    /**
     * 将目标压缩文件解压到destFloder
     *
     * @param destFloder
     * @param zipFilePath
     * @return
     */
    public static String unzipFile(String destFloder, String zipFilePath) {
        if (!FileUtil.createFloderIfNotExist(destFloder)) {
            return null;
        }

        File zipFile = new File(zipFilePath);
        if (!zipFile.exists() || !zipFile.isFile()) {
            return null;
        }

        String tempUnZipFloderName =
                Paths.get(
                        destFloder, String.format("%s_%s", zipFile.getName(), UUID.randomUUID().toString()))
                        .toString();
        if (!FileUtil.createFloderIfNotExist(tempUnZipFloderName)) {
            return null;
        }

        try (FileInputStream fileInputStream = new FileInputStream(zipFile)) {
            FileUtil.unzipFileInputStream(tempUnZipFloderName, fileInputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new File(tempUnZipFloderName).getAbsolutePath();
    }

    /**
     * 将multipartFile解压到destFloder
     *
     * @param destFloder
     * @param multipartFile
     * @return
     */
    public static String unzipFile(String destFloder, MultipartFile multipartFile) {
        if (!FileUtil.createFloderIfNotExist(destFloder)) {
            return null;
        }

        String tempUnZipFloderName =
                Paths.get(
                        destFloder,
                        String.format(
                                "%s_%s", multipartFile.getOriginalFilename(), UUID.randomUUID().toString()))
                        .toString();
        if (!FileUtil.createFloderIfNotExist(tempUnZipFloderName)) {
            return null;
        }

        try (FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream()) {
            FileUtil.unzipFileInputStream(tempUnZipFloderName, fileInputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new File(tempUnZipFloderName).getAbsolutePath();
    }

    private static void unzipFileInputStream(String rootFloder, FileInputStream fileInputStream) {
        byte[] buffer = new byte[2048];
        try (ZipInputStream zipInputStream = new ZipInputStream(fileInputStream)) {
            ZipEntry entry = zipInputStream.getNextEntry();

            while (entry != null) {
                String entryName = entry.getName();
                File file = Paths.get(rootFloder, entryName).toFile();

                if (entry.isDirectory()) {
                    File newDir = new File(file.getAbsolutePath());
                    if (!newDir.exists()) {
                        boolean success = newDir.mkdirs();
                        if (!success) {
                            log.info("Problem creating Folder");
                        }
                    }
                } else {
                    try (FileOutputStream fOutput = new FileOutputStream(file)) {
                        int count = 0;
                        while ((count = zipInputStream.read(buffer)) > 0) {
                            // write 'count' bytes to the file output stream
                            fOutput.write(buffer, 0, count);
                        }
                    }
                }

                zipInputStream.closeEntry();
                entry = zipInputStream.getNextEntry();
            }

            zipInputStream.closeEntry();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (("").equals(file) || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(System.getProperty("java.io.tmpdir"), file.getOriginalFilename());
            if (toFile.exists()) {
                toFile.delete();
            }
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    // 获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本地临时文件
     *
     * @param file
     */
    public static void deleteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }

}
